/*
 * Copyright 2011 Rolf Aden
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.ec;

import java.util.Arrays;
import java.util.List;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Mapper;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * Utility class to help track errors and display them to the user.
 * 
 * @author Rolf Aden
 */
class ErrorReporter {
	private final static int MAX_ERRORS = 20;
	
	private Mapper<Key,Entity,NullWritable,NullWritable>.Context context;
	private DatastoreService ds;
	
	ErrorReporter(Mapper<Key,Entity,NullWritable,NullWritable>.Context context, DatastoreService ds) {
		this.context = context;
		this.ds = ds;
	}
	
	void addErrorMessage(String errMsg) {
		String errId = context.getTaskAttemptID().toString();
		Key errKey = KeyFactory.createKey("EntityConsoleError", errId);
		Entity err;
		try {
			err = ds.get(errKey);
			@SuppressWarnings("unchecked")
			List<String> msg = (List<String>)err.getProperty("message");
			if (msg.size() < MAX_ERRORS) {
				msg.add(errMsg);
				ds.put(err);
			} else if (msg.size() == MAX_ERRORS){
				msg.add(errMsg);
				msg.add("there are more unreported errors!");
				ds.put(err);
			}
		} catch (EntityNotFoundException e) {
			err = new Entity("EntityConsoleError", errId);
			err.setProperty("message", Arrays.asList(errMsg));
			ds.put(err);
		}
	}
	
}
